//
//  XGLPersonalRequestAPI.swift
//  XGamesLive
//
//  Created by ios on 2024/5/17.
//

import Foundation
import PanKit
import Moya
import SwiftyRSA

class XGLPersonalRequestAPI: PanRequestBaseAPI,XGL_RequestConfigurationProtocol {
    enum CustomAPI{
        case SurplusCoin
        case MyVideos(page: NSInteger,size: NSInteger)
        case MyThumbVideos(page: NSInteger,size: NSInteger)
        case PersonalInfor
        case UpdateuserData(header: String?,nickName: String)
        case userData(userId: String)
        case UserVideos(userId: String,page: NSInteger,size: NSInteger)
        case PublishData(data: PublishParamsData)
        case GetPublishData(userId: String?,page: NSInteger,size: NSInteger,data1: String,pid: String?,data5: String?)
        case GetActionDatas(type: String,page: NSInteger,size: NSInteger)
        ///type:  2 like 3 comment  action actionResult: ture or false
        case Handler(auditTreeDataId: String,type: NSInteger,actionResult: Bool)
        case CheckAction(id: String,type: String)
        case DeleteTreeData(id: String)
        case ReportTreeData(id: String,reason: String)
        ///blacklist
        case AddBlacklist(userId: String)
        case BlacklistPage(page: NSInteger,size: NSInteger)
        case DeleteBlacklist(userId: String)
        
        case Follow(userId: String,isFollow: Bool)
        case Followers(page: NSInteger,size: NSInteger)
        case Fans(page: NSInteger,size: NSInteger)
        case IsFollowUser(userId: String)
        case FollowsAndFansNum
        case UserFollowsAndFansNum(userId: String)
        
        case RecievedGifts(userId: String)
        
        case DeleteAccount
    }
    
    init(requestAPI: CustomAPI) {
        super.init()
        self.resuestAPI = requestAPI
        self.requestConfiguration()
    }
    private var resuestAPI: CustomAPI!
    
    override var path: String{
        switch self.resuestAPI {
        case .SurplusCoin:
            return "/BerryApi/users/getMyAsset"
        case .PersonalInfor:
            return "/BerryApi/\(randomString())/getCurUser\(randomString())Ext"
        case .MyVideos:
            return "/BerryApi/videos/listMyVideo"
        case .MyThumbVideos:
            return "/BerryApi/videos/listLikeVideo"
        case .userData:
            return "/BerryApi/\(randomString())/get\(randomString())UserExtByUserId"
        case .UpdateuserData:
            return "/BerryApi/users/update"
        case .UserVideos:
            return "/BerryApi/videos/listVideoByUserId"
        case .PublishData:
            return "/BerryApi/\(randomString())/addOrEdit\(randomString())TreeData"
        case .GetPublishData:
            return "/BerryApi/\(randomString())/findPage\(randomString())TreeData"
        case .GetActionDatas:
            return "/BerryApi/\(randomString())/listActioned\(randomString())TreeData"
        case .Handler(_,_,let actionResult):
            if actionResult{
                return "/BerryApi/\(randomString())/action\(randomString())TreeData"
            }
            return "/BerryApi/\(randomString())/unAction\(randomString())TreeData"
        case .CheckAction:
            return "/BerryApi/\(randomString())/checkAction\(randomString())TreeData"
        case .DeleteTreeData(let id):
            return "/BerryApi/\(randomString())/delete\(randomString())TreeData/\(id)"
        case .ReportTreeData:
//            return "/BerryApi/\(randomString())/report\(randomString())TreeData"
            return "/BerryApi/users/feedback"
        case .AddBlacklist:
            return "/BerryApi/blacklists/addBlacklist"
        case .BlacklistPage:
            return "/BerryApi/blacklists/listBlacklist"
        case .DeleteBlacklist:
            return "/BerryApi/blacklists/cancelBlacklist"
        case .Follow(_,let isFollow):
            if isFollow{
                return "/BerryApi/followers/following"
            }
            return "/BerryApi/followers/cancelFollowing"
        case .IsFollowUser:
            return "/BerryApi/followers/checkAuthor"
        case .Followers:
            return "/BerryApi/followers/listFollowing"
        case .Fans:
            return "/BerryApi/followers/listFollower"
        case .FollowsAndFansNum:
            return "/BerryApi/users/getMydetail"
        case .UserFollowsAndFansNum:
            return "/BerryApi/users/detail"
        case .DeleteAccount:
            return "/BerryApi/users/delete"
        case .RecievedGifts:
            return "/BerryApi/gift/getGiftStatistic"
        default:
            return ""
        }
    }
    
    override var method: Moya.Method{
        switch self.resuestAPI {
        case .MyVideos,.MyThumbVideos,.userData,.UserVideos,.PublishData,.GetPublishData,.GetActionDatas,.Handler,.CheckAction,.ReportTreeData,.AddBlacklist,.DeleteBlacklist,.DeleteAccount,.Follow,.IsFollowUser,.UpdateuserData:
            return .post
        case .DeleteTreeData:
            return .delete
        default:
            return .get
        }
    }
    
    override var task: Task{
        switch self.resuestAPI {
        case .MyVideos,.MyThumbVideos,.userData,.UserVideos,.PublishData,.GetPublishData,.GetActionDatas,.Handler,.CheckAction,.ReportTreeData,.AddBlacklist,.DeleteBlacklist,.DeleteAccount,.Follow,.IsFollowUser,.UpdateuserData:
            return .requestParameters(parameters: parameters, encoding: JSONEncoding.default)
        default:
//            if parameters.isEmpty == false{
//                let parameStr = parameters.map { "\($0.key)=\($0.value)" }.joined(separator: "&")
//                let rsaParams = XGL_PRSA.encryptString(parameStr, publicKey: XGL_EncipherTool.share.cpk)
//                return .requestParameters(parameters: ["encryptParam": rsaParams ?? ""],encoding: parameterEncoding)
//            }
            if parameters.isEmpty == false{
                let parameStr = parameters.map { "\($0.key)=\($0.value)" }.joined(separator: "&")
                do {
                    let publicKey = try PublicKey(base64Encoded: XGL_EncipherTool.share.cpk)
                    let encryptedStr = try ClearMessage(string: parameStr, using: .utf8).encrypted(with: publicKey, padding: .PKCS1)
                    return .requestParameters(parameters: ["encryptParam": encryptedStr.base64String],encoding: parameterEncoding)
                } catch {
                print(error)
                }
            }
            return .requestParameters(parameters: parameters,encoding: parameterEncoding)
        }
    }
    
    override var cacheModel: PanRequestBaseAPI.PanRequestCacheModel{
        return .none
    }
    
    override var cacheKey: String{
        return "test"
    }
    
    override var parameters: [String : Any]{
        var dic = super.parameters
        switch self.resuestAPI {
        case .MyVideos(let page,let size):
            dic["page"] = page
            dic["size"] = size
            return dic
        case .MyThumbVideos(let page,let size):
            dic["page"] = page
            dic["size"] = size
            return dic
        case .userData(let userId):
            dic["userId"] = userId
            return dic
        case .UpdateuserData(let header,let nickName):
            if let value = header {
                dic["header"] = value
            }
            dic["nickname"] = nickName
            return dic
        case .UserVideos(let userId,let page,let size):
            dic["userId"] = userId
            dic["page"] = page
            dic["size"] = size
            return dic
        case .PublishData(let data):
            if let params = data.toDictionary(){
                return self.mergeJSON(dic, with: params)
            }
            return dic
        case .GetPublishData(let userId,let page,let size,let data1,let pid,let data5):
            if let value = userId {
                dic["userId"] = value
            }
            dic["page"] = page
            dic["size"] = size
            dic["data1"] = data1
            if let value = pid {
                dic["pid"] = value
            }
            if let value = data5 {
                dic["data5"] = value
            }
            return dic
        case .GetActionDatas(let type,let page,let size):
            dic["page"] = page
            dic["size"] = size
            dic["type"] = type
            return dic
        case .Handler(let auditTreeDataId,let type, _):
            dic["auditTreeDataId"] = auditTreeDataId
            dic["type"] = type
            return dic
        case .CheckAction(let id,let type):
            dic["auditTreeDataId"] = id
            dic["type"] = type
            return dic
        case .ReportTreeData(let id,let reason):
//            dic["auditTreeDataId"] = id
            dic["content"] = reason
            return dic
        case .AddBlacklist(let userId):
            dic["userId"] = userId
            return dic
        case .BlacklistPage(let page,let size):
            dic["page"] = page
            dic["size"] = size
            return dic
        case .DeleteBlacklist(let userId):
            dic["userId"] = userId
            return dic
        case .Follow(let userId, _):
            dic["userId"] = userId
            return dic
        case .Followers(let page,let size):
            dic["page"] = page
            dic["size"] = size
            return dic
        case .Fans(let page,let size):
            dic["page"] = page
            dic["size"] = size
            return dic
        case .UserFollowsAndFansNum(let userId):
            dic["userId"] = userId
            return dic
        case .IsFollowUser(let userId):
            dic["userId"] = userId
            return dic
        case .RecievedGifts(let userId):
            dic["userId"] = userId
            return dic
        default:
            return dic
        }
    }
    
    func mergeJSON(_ json1: [String: Any], with json2: [String: Any]) -> [String: Any] {
        var mergedJSON = json1
        for (key, value) in json2 {
            if let nestedJSON = value as? [String: Any],
               let existingNestedJSON = mergedJSON[key] as? [String: Any] {
                mergedJSON[key] = mergeJSON(existingNestedJSON, with: nestedJSON)
            } else {
                mergedJSON[key] = value
            }
        }
        return mergedJSON
    }
}

